package com.cs.cashbox.module;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Scope;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.filter.CheckSession;

import com.cs.cashbox.bean.User;
import com.cs.cashbox.util.Toolkit;

@Filters(@By(type = CheckSession.class, args = { "me", "/" }))
@IocBean
@At("/user")
@Ok("json:{locked:'password|salt',ignoreNull:true}")
@Fail("http:500")
public class UserModule extends BaseModule {

	public static final Log log = Logs.get();

	@At
	public int count() {
		return dao.count(User.class);
	}

	@Filters()
	@At
	public Object login(
			@Param("userID") String userID,
			@Param("password") String password,
			@Param("captcha") String captcha,
			@Attr(scope = Scope.SESSION, value = "nutz_captcha") String _captcha,
			HttpSession session) {
		NutMap re = new NutMap();
		if (!Toolkit.checkCaptcha(_captcha, captcha)) {
			return re.setv("ok", false).setv("msg", "验证码错误");
		}
		User user = dao.fetch(User.class, Cnd.where("userID", "=", userID).and("password", "=",password));
		if (user == null) {
			 return re.setv("ok", false).setv("msg", "用户名或密码错误");
		}else{
			session.setAttribute("userID", userID);
			session.setAttribute("me", userID);
			return re.setv("ok", true);
			
		}
	}

	@At
	@Ok(">>:/")
	public void logout(HttpSession session) {
		session.invalidate();
	}

	protected String checkUser(User user, boolean create) {
		if (user == null) {
			return "空对象";
		}
		if (create) {
			if (Strings.isBlank(user.getUserID())
					|| Strings.isBlank(user.getPassword()))
				return "用户名/密码不能为空";
		} else {
			if (Strings.isBlank(user.getPassword()))
				return "密码不能为空";
		}
		String passwd = user.getPassword().trim();
		if (6 > passwd.length() || passwd.length() > 12) {
			return "密码长度错误,6-12个字符之间";
		}
		user.setPassword(passwd);
		if (create) {
			int count = dao.count(User.class,
					Cnd.where("userID", "=", user.getUserID()));
			if (count != 0) {
				return "用户ID已经存在";
			}
		}
		if (user.getUserID() != null)
			user.setUserID(user.getUserID().trim());
		return null;
	}

	@At
	public Object add(@Param("..") User user) {
		NutMap re = new NutMap();
		String msg = checkUser(user, true);

		if (msg != null) {
			return re.setv("ok", false).setv("msg", msg);
		}
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());
		user = dao.insert(user);
		return re.setv("ok", true).setv("data", user);
	}

	@At
	public Object update(@Param("..") User user) {
		NutMap re = new NutMap();
		String msg = checkUser(user, false);
		if (msg != null) {
			return re.setv("ok", false).setv("msg", msg);
		}
		user.setUserID(null);// 不允许更新用户名
		user.setCreateTime(null);// 也不允许更新创建时间
		user.setUpdateTime(new Date());// 设置正确的更新时间
		dao.updateIgnoreNull(user);// 真正更新的其实只有password和salt
		return re.setv("ok", true);
	}

	@At
	@Aop(TransAop.READ_COMMITTED)
	public Object delete(@Param("userID") String userID, @Attr("me") String me) {
		if (me == userID) {
			return new NutMap().setv("ok", false).setv("msg", "不能删除当前用户!!");
		}
		dao.delete(User.class, userID);// 再严谨一些的话,需要判断是否为>0
		return new NutMap().setv("ok", true);
	}

	@At
	public Object query(@Param("userID") String userID,
			@Param("userName") String userName, @Param("..") Pager pager) {
		Cnd cnd = (Strings.isBlank(userID) && Strings.isBlank(userName)) ? null
				: Cnd.where("userID", "like", "%" + userID + "%").or(
						"userName", "like", "%" + userName + "%");
		QueryResult qr = new QueryResult();
		qr.setList(dao.query(User.class, cnd, pager));
		pager.setRecordCount(dao.count(User.class, cnd));
		qr.setPager(pager);
		return qr; // 默认分页是第1页,每页20条
	}

	@At
	@Ok("jsp:jsp.user.list")
	public void index() {
	}
}
